package com.duowan.cms.intf.duowanvote;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;

import org.springframework.stereotype.Service;

import com.duowan.cms.common.exception.BaseCheckedException;
import com.duowan.cms.common.util.NetUtil;
import com.duowan.cms.common.util.StringUtil;
import com.duowan.cms.intf.Constants;

@Service("duowanVoteRemoteService")
public class DuowanVoteServiceImpl implements DuowanVoteRemoteService {

    private static final String CODE_SUCCESS = "201";
    
    @Override
    public LinkedHashMap<Long, Long> getVoteRankDataByArticles(DuowanVoteSearchCriteria criteria) {

        Map<String, String> paramsMap = new HashMap<String, String>();// 参数map
        paramsMap.put("channelId", criteria.getChannelId());
        paramsMap.put("tag", criteria.getTag());
        paramsMap.put("status", criteria.getStatus().toString());
        paramsMap.put("type", criteria.getType().toString());
        paramsMap.put("start", criteria.getStart().toString());
        paramsMap.put("size", criteria.getSize().toString());
        // 投票系统已经取消了自定义日期排行
        // paramsMap.put("startDate", criteria.getStartDate());
        // paramsMap.put("endDate", criteria.getEndDate());
        paramsMap.put("queryType", criteria.getQueryType());
        paramsMap.put("articleIds", criteria.getArticleIds());
        String responseData = null;
        try {
            responseData = NetUtil.postHttpRequest(paramsMap, Constants.VOTE_URL, Constants.EXPIRE_SECONDS);
            String jsonData = parseResponseData(responseData);
            return parseJSONData(jsonData);
        } catch (BaseCheckedException e) {
            logger.warn("与投票系统交互(获取排行数据)出错!!!", e);
        } catch (Exception e) {
            logger.warn("获取排行数据后解析出错!!!投票系统返回数据：" + responseData, e);
        }
        return new LinkedHashMap<Long, Long>();
    }
    
    /**
     * 解析返回的文本数据
     * @param responseData
     * @return 排行榜数据
     * @throws Exception
     */
    private String parseResponseData(String responseData) throws Exception {
        if (StringUtil.isEmpty(responseData)) {
            throw new Exception("the response string is empty");
        }
        
        List<String> returnStrs = new ArrayList<String>();
        for(String str : responseData.split("\\n")){
            returnStrs.add(str);
        }
        
        String jsonData = "";
        if (returnStrs.size() < 2) {
            throw new Exception("the response string is wrong!response string:" + responseData);
        }
        String code = returnStrs.get(0);
        if (!CODE_SUCCESS.equals(code)) {
            logger.error("response error code! error description:" + returnStrs.get(1));
            throw new Exception(returnStrs.get(1));
        } else {
            if (returnStrs.size() != 4) {
                throw new Exception("the response string is wrong!response string:" + responseData);
            }
            jsonData = returnStrs.get(3);
        }
        return jsonData;
    }
    
    
    /**
     * 解析json格式数据
     * 
     * @param list
     * @param cb
     * @throws JSONException
     */
    private LinkedHashMap<Long, Long> parseJSONData(String jsonData) {
        LinkedHashMap<Long, Long> map = new LinkedHashMap<Long, Long>();
        JSONArray jsonArray = JSONArray.fromObject(jsonData);
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jObj = jsonArray.getJSONObject(i);
            Long articleId = jObj.getLong("articleId");
            Long votenum = jObj.getLong("votenum");
            map.put(articleId, votenum);
        }
        return map;
    }
    
    @SuppressWarnings("deprecation")
    @Override
    public Integer getVoteNum(String articleId, String channelId, String title, String url) {

        
        Map<String, String> postParamsMap =  putLoadVoteParameterInMap(new HashMap<String, String>());
        postParamsMap.put("articleId", articleId);
        postParamsMap.put("channelId", channelId);
        postParamsMap.put("title", URLEncoder.encode(URLEncoder.encode(title)));
        postParamsMap.put("url", URLEncoder.encode(URLEncoder.encode(url)));
        
        String responseData = null;
        try {
            responseData = NetUtil.postHttpRequest(postParamsMap, Constants.VOTE_OR_LOAD_URL, Constants.EXPIRE_SECONDS);
            return getVoteNumFromResponseData(responseData);
        } catch (BaseCheckedException e) {
            logger.warn("getVoteNum fail!!加载投票数据请求失败!", e);
        } catch (Exception e) {
            logger.warn("getVoteNum 返回数据解析出错!" + responseData, e);
        }
        return 0;
    }
    
    /**
     * 解析加载投票数据请求返回的数据
     * @param responseData
     * @return
     * @throws Exception
     */
    private Integer getVoteNumFromResponseData(String responseData) throws Exception{
        int result = 0;
        int index = responseData.indexOf("total value='");
        if (index != -1){
            String end = responseData.substring(index + "total value='".length());
            index = end.indexOf("' statusId='1'");
            if (index != -1){
                end = end.substring(0,index);
                result = Integer.parseInt(end);
            }
        }
        return result;
    }
    
    private Map<String, String> putLoadVoteParameterInMap(Map<String, String> postParamsMap) {
        String divId = "divId";
        String justShowSum="0";
        String type="5";
        String status="8";
        String tag="statistics";
        String isLoad="1";
        String encode="utf-8";
        String picurl = "picurl";
        
        postParamsMap.put("divId", divId);
        postParamsMap.put("monthMum", "0");
        postParamsMap.put("justShowSum", justShowSum);
        postParamsMap.put("type", type);
        postParamsMap.put("status", status);
        postParamsMap.put("tag", tag);
        postParamsMap.put("isLoad", isLoad);
        postParamsMap.put("encode", encode);
        postParamsMap.put("picurl", picurl);
        return postParamsMap;
    }

}
